package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import splug.cjk.packet.MessagePacket;

public class MessageWrite extends Thread {

	private InputStream is;
	private OutputStream os;

	public MessageWrite(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}

	@Override
	public void run() {
		super.run();
		try {
			/**
			 * 액티비티에 입력된 정보들을 모두 받아온다
			 */
			ObjectInputStream input = new ObjectInputStream(is);
			MessagePacket packet = (MessagePacket) input.readObject();
			String id = packet.getId();
			String send = packet.getSend();
			String comment = packet.getComment();
			String date = packet.getDate();

			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();
			
			/**
			 * member 테이블에 해당하는 사람이 있는지 확인한다
			 */
			String query1 = "select id from member;";

			ResultSet rs = stmt.executeQuery(query1);

			while(rs.next()){
				String str = rs.getString("id");
				//해당하는 사람이 있으면 쪽지를 보낸다
				if(str.equals(send)){
					String query = "insert into message (`f`,`t`,`comment`,`date`) values ('" + id + "','" + send + "','" + comment + "','" + date + "')";
					
					stmt.execute("SET CHARACTER SET euckr");
					stmt.execute("set names euckr");

					stmt.executeUpdate(query);

					os.write('1');
					os.flush();
					return;
				}

			}
			/**
			 * 해당하는 사람이 없으면 클라이언트에게 '0'을 보내준다
			 */
			os.write('0');
			os.flush();
			

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
